package com.cb.common.webapp.context;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;

import com.cb.domain.model.system.SystemUser;
import com.cb.domain.model.user.UserAccount;

public class RequestContext {
	private static final Log logger=LogFactory.getLog(RequestContext.class);
	
	/**
	 * 从上下文取得当前用户
	 * @return
	 */
	public static UserAccount getCurrentUser(){
		SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            Authentication auth = securityContext.getAuthentication();
            if (auth != null && auth.getPrincipal() instanceof UserAccount) {
                Object principal = auth.getPrincipal();
                return (UserAccount) principal;
            } else {
                logger.warn("WARN: User cannot be lookuped using SecurityContextHolder.");
            }
        }
        return null;
	}
	
/*	*//**
	 * 从上下文取得当前用户
	 * @return
	 *//*
	public static UserCompany getCompanyUser(){
		SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            Authentication auth = securityContext.getAuthentication();
            if (auth != null && auth.getPrincipal() instanceof UserCompany) {
                Object principal = auth.getPrincipal();
                return (UserCompany) principal;
            } else {
                logger.warn("WARN: UserCompany cannot be lookuped using SecurityContextHolder.");
            }
        }
        return null;
	}
	*/
	/**
	 * 从上下文取得当前用户
	 * @return
	 */
	public static SystemUser getCurrentSystemUser(){
		SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            Authentication auth = securityContext.getAuthentication();
            if (auth != null && auth.getPrincipal() instanceof SystemUser) {
                Object principal = auth.getPrincipal();
                return (SystemUser) principal;
            } else {
                logger.warn("WARN: SystemUser cannot be lookuped using SecurityContextHolder.");
            }
        }
		SystemUser adminUser = new SystemUser();
		return adminUser;
	}
	
}
